"use client";

import { ProLayout as AntProLayout } from "@ant-design/pro-components";
import {
  DashboardOutlined,
  BookOutlined,
  TeamOutlined,
  CommentOutlined,
  UserOutlined,
  LogoutOutlined,
} from "@ant-design/icons";
import { useSession, signOut } from "next-auth/react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { Avatar, Dropdown, type MenuProps, App } from "antd";
import { useNotification } from "~/components/common/Notification";

export default function ProLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const router = useRouter();
  const { data: session } = useSession();
  const [mounted, setMounted] = useState(false);
  const { message } = App.useApp();
  const notification = useNotification();

  useEffect(() => {
    setMounted(true);
  }, []);

  const isTeacher = session?.user?.role === "TEACHER";
  const isAdmin = session?.user?.role === "ADMIN";

  const handleLogout = async () => {
    try {
      await signOut({ redirect: false });
      notification.success({
        message: "退出登录成功",
        description: "正在跳转到登录页面...",
      });
      router.push("/login");
    } catch (error) {
      notification.error({
        message: "退出登录失败",
        description: "请稍后重试",
      });
    }
  };

  const userMenuItems: MenuProps["items"] = [
    {
      key: "profile",
      label: <Link href="/profile">个人信息</Link>,
      icon: <UserOutlined />,
    },
    {
      type: "divider",
    },
    {
      key: "logout",
      label: "退出登录",
      icon: <LogoutOutlined />,
      onClick: handleLogout,
    },
  ];

  if (!mounted) {
    return <div className="min-h-screen bg-gray-100" />;
  }

  return (
    <AntProLayout
      title="在线教育平台"
      logo={null}
      layout="mix"
      splitMenus={false}
      contentWidth="Fluid"
      fixedHeader
      fixSiderbar
      avatarProps={{
        src: session?.user?.image ?? undefined,
        size: "small",
        title: session?.user?.name,
        render: (props, dom) => (
          <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
            {dom}
          </Dropdown>
        ),
      }}
      location={{
        pathname,
      }}
      route={{
        path: "/",
        routes: [
          {
            path: "/dashboard",
            name: "仪表盘",
            icon: <DashboardOutlined />,
          },
          ...(isTeacher || isAdmin ? [
            {
              path: "/courses",
              name: "课程管理",
              icon: <BookOutlined />,
            },
          ] : []),
          {
            path: "/my-courses",
            name: "我的课程",
            icon: <BookOutlined />,
          },
          ...(isAdmin ? [
            {
              path: "/users",
              name: "用户管理",
              icon: <TeamOutlined />,
            },
          ] : []),
          {
            path: "/forum",
            name: "学校论坛",
            icon: <CommentOutlined />,
          },
        ],
      }}
      menuItemRender={(item, dom) => (
        <Link href={item.path ?? "#"}>{dom}</Link>
      )}
    >
      {children}
    </AntProLayout>
  );
}